import traceback

import numpy as np
from django.db.models import Avg

from User.models import Rating, ClickNum, Comment, GameComment


def sigmoid(num):
    return 1 / (1 + np.exp(-num))


def tanh(x):
    return (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))


def getsore(ClickNum, rating):
    return 5 * sigmoid(1.5 * sigmoid(ClickNum - 3) + 4 * tanh((rating - 3) / 5))


def update_rating(userId, gameId):
    try:
        click = ClickNum.objects.get(userId=userId, gameId=gameId).click
    except ClickNum.DoesNotExist:
        click = 0
    comment_score = 0
    try:
        comment = GameComment.objects.filter(userid=int(userId), gameid=int(gameId))
        comment_score = comment.aggregate(avg=Avg("score"))['avg']
        if comment_score is None:
            comment_score = 3
        if comment_score == 0:
            comment_score = 3
    except Exception:
        traceback.print_exc()
    finally:
        newrating = getsore(click, comment_score)
        user_rate = Rating.objects.filter(userId=userId, gameId=gameId)
        if user_rate.count() != 0:
            user_rate.update(rating=newrating)
            pass
        else:
            create = Rating(userId=userId, gameId=gameId, rating=newrating)
            create.save()
            pass


if __name__ == "__main__":
    update_rating(9, 2383)
